package com.googlecode.dgwt.client.dijit;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.HasHTML;
import com.googlecode.dgwt.client.dijit.base.widget.WidgetEngine;
import com.googlecode.dgwt.client.dijit.util.Template;
import com.googlecode.dgwt.client.dojo.Dojo;
import com.googlecode.dgwt.client.dojo.URL;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class HTML extends Widget implements HasHTML {


    public HTML() {
        super(Document.get().createSpanElement());
    }

    
    public HTML(String html) {
        super(false);
        loadFromHTML(this, html, "span");
        postCreate();
    }

    
    public HTML(URL url) {
        super(false);
        loadFromTemplate(new Template(url));
        postCreate();
    }

    
    public HTML(Element element) {
        super(false);
        loadFromTemplate(new Template(element));
        postCreate();
    }

    
    protected HTML(boolean ready) {
        super(ready);
    }


    public String getText() {
        return getContainerElement().getInnerText();
    }
    
    
    public void setText(String text) {
        getContainerElement().setInnerText(text);
    }

    
    public String getHTML() {
        return getContainerElement().getInnerHTML();
    }
    
    
    public void setHTML(String html) {
        getContainerElement().setInnerHTML(html);
    }
    

    static Template loadFromHTML(Widget widget, String html, String wrapperTagName){
        
        if (html != null && (html.indexOf("<") >= 0 || Dojo.string.isParameterized(html))){
            Template template = new Template(html);
            WidgetEngine.get(widget).loadFromTemplate(template, widget);
            return template;
        }

        widget.setDomElement(Document.get().createElement(wrapperTagName));
        
        if (html != null){
            widget.getElement().setInnerHTML(html);
        }
        
        return null;
    }
    
}